package com.hanxiaozhang.smallfunction.count;

/**
 * 〈一句话功能简述〉<br>
 * 〈统计字符串出现的次数〉
 *
 * @author hanxinghua
 * @create 2023/5/18
 * @since 1.0.0
 */
public class No1CountSubString {

    public static void main(String[] args) {

        String str = "&1!&2&3&4&5";

        System.out.println(count(str,"&"));

    }


    /**
     *  参考spring工具类
     *  org.springframework.util.StringUtils#countOccurrencesOf
     *
     * @param str
     * @param sub
     * @return
     */
    public static int count(String str, String sub) {
        // 重复出现个数
        int count = 0;
        // 开始查找的位置
        int fromIndex = 0;
        // 当前索引值
        int idx;
        while ((idx = str.indexOf(sub, fromIndex)) != -1) {
            ++count;
            fromIndex = idx + sub.length();
        }
        return count;
    }


}
